package com.neusoft.bd.myflink.step06;

import cn.hutool.core.date.DateUtil;
import com.neusoft.bd.myflink.entity.WaterSensor;
import com.neusoft.bd.myflink.source.WaterSensorSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RichAggregateFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.Date;

public class WindowProcessDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        System.out.println(DateUtil.formatDateTime(new Date()));

        DataStreamSource<WaterSensor> stream =
                env.fromSource(
                        WaterSensorSource.waterSensorDataStreamSource(),
                        WatermarkStrategy.noWatermarks(),
                        "Generator Source");
        WindowedStream<WaterSensor, String, TimeWindow> window = stream.keyBy(ws -> ws.getId())
                .window(TumblingProcessingTimeWindows.of(Time.seconds(10)));
        SingleOutputStreamOperator<String> process = window
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {

                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        long count = elements.spliterator().estimateSize();
                        long windowStartTs = context.window().getStart();
                        long windowEndTs = context.window().getEnd();
                        String windowStart = DateUtil.formatDateTime(new Date(windowStartTs));
                        String windowEnd = DateUtil.formatDateTime(new Date(windowEndTs));
                        out.collect("key=" + s + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements.toString());

                    }
                });
        process.print();

        env.execute();

    }
}
